/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.util;

import java.math.BigDecimal;

/**
 * 
 * @author haolw
 * @time 2017/10/18
 */
public abstract class MathUtil {
	
	/** 默认除法运算精度 */
	private static final int DEF_DIV_SCALE = 10;

	/**
	 * Double加法
	 * 
	 * @param v1
	 * @param v2
	 * @return
	 */
	public static Double add(Double v1, Double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.add(b2).doubleValue();
	}

	/**
	 * Double减法
	 * 
	 * @param v1
	 * @param v2
	 * @return
	 */
	public static Double sub(Double v1, Double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.subtract(b2).doubleValue();
	}

	/**
	 * Double乘法
	 * 
	 * @param v1
	 * @param v2
	 * @return
	 */
	public static Double mul(Double v1, Double v2) {
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.multiply(b2).doubleValue();
	}

	/**
	 * Double除法
	 * 
	 * @param v1
	 * @param v2
	 * @return
	 */
	public static Double div(Double v1, Double v2) {
		return div(v1, v2, DEF_DIV_SCALE);
	}

	/**
	 * Double除法，精度以后的数字四舍五入
	 * 
	 * @param v1
	 * @param v2
	 * @return
	 */
	public static Double div(Double v1, Double v2, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException("The scale must be a positive integer or zero");
		}
		BigDecimal b1 = new BigDecimal(Double.toString(v1));
		BigDecimal b2 = new BigDecimal(Double.toString(v2));
		return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

}
